package com.gj;


import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Main {

    public static final ThreadPoolExecutor EXECUTOR = new ThreadPoolExecutor(
            10,
            100,
            10,
            TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(100)
    );


    public static Integer stock = 100;


    public static void main(String[] args) throws Exception {
        testMyLock();

//        interProcessMutex();

//        testReentrant();

    }

    private static void testMyLock() {
        DistributedLock distributedLock = new DistributedLock("/lock/product-");

        for (int i = 0; i < 100; i++) {
            EXECUTOR.execute(() -> {
                try {
                    distributedLock.lock();
                    Main.stock = Main.stock - 1;
                    System.out.println("扣减库存，当前库存: " + Main.stock);
                    Thread.sleep(1000);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    distributedLock.unlock();
                }
            });
        }
    }

    private static void testReentrant() {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString("127.0.0.1:2181")
                .sessionTimeoutMs(5000)
                .retryPolicy(retryPolicy)
                .build();
        //开启连接
        client.start();
        InterProcessMutex mutex = new InterProcessMutex(client, "/lock/product-1");

        for (int i = 0; i < 10; i++) {
            EXECUTOR.execute(() -> {
                try {
                    mutex.acquire();
                    mutex.acquire();
                    System.out.println("测试锁重入");
                    //具体的业务逻辑
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    try {
                        mutex.release();
                        mutex.release();
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
            });
        }
    }


    private static void interProcessMutex() {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString("127.0.0.1:2181")
                .sessionTimeoutMs(5000)
                .retryPolicy(retryPolicy)
                .build();
        //开启连接
        client.start();
        InterProcessMutex mutex = new InterProcessMutex(client, "/lock/product-");

        for (int i = 0; i < 100; i++) {
            EXECUTOR.execute(() -> {
                try {
                    mutex.acquire();
                    Main.stock = Main.stock - 1;
                    System.out.println("扣减库存，当前库存: " + Main.stock);
                    Thread.sleep(1000);
                    //具体的业务逻辑
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    try {
                        mutex.release();
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
            });
        }
    }


    public static void lock() throws Exception {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString("127.0.0.1:2181")
                .sessionTimeoutMs(5000)
                .retryPolicy(retryPolicy)
                .build();
        //开启连接
        client.start();
        InterProcessMutex mutex = new InterProcessMutex(client, "/lock/product-1");
        try {
            mutex.acquire();

            //具体的业务逻辑
        } finally {
            mutex.release();
        }
    }
}
